import psutil
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from scapy.all import *


# 获取系统中所有网卡接口
def get_interfaces():
    interfaces = psutil.net_if_addrs()
    interface_names = list(interfaces.keys())
    return interface_names

# 上传文件并处理
def upload_file():
    file_path = filedialog.askopenfilename(filetypes=[("PCAP files", "*.pcap"), ("PCAP files", "*.pcapng"), ("All files", "*.*")])
    if file_path:
        file_path_label.config(text=file_path)

# 开始重放数据包
def start_replay():
    selected_interface = select_adapter_box.get()
    file_path = file_path_label.cget("text")

    if not selected_interface:
        messagebox.showerror("Error", "请选择一张可用网卡")
        return
    if not file_path:
        messagebox.showerror("Error", "请上传一个有效数据包文件")
        return

    try:
        packets = rdpcap(file_path)  # 读取pcap文件中的数据包
        for packet in packets:
            sendp(packet, iface=select_adapter_box.get(), verbose=0)  # 发送数据包到指定网卡
            print(f"Replaying packet: {packet.summary()}")  # 打印重放的数据包摘要
        messagebox.showinfo("Info", "数据包重放完毕")
    except Exception as e:
        messagebox.showerror("Error", f"Error: {e}")


# 创建主窗口
root = tk.Tk()
root.title("数据包重放器")

# 创建选择网卡标签和下拉框
select_adapter_label = ttk.Label(root, text="选择网卡:")
select_adapter_label.grid(row=0, column=0, padx=10, pady=10)

interfaces = get_interfaces()
selected_adapter = tk.StringVar()
select_adapter_box = ttk.Combobox(root, textvariable=selected_adapter, values=interfaces, width=50)
select_adapter_box.grid(row=0, column=1, padx=10, pady=10)

# 创建上传文件按钮和显示文件路径的标签
upload_file_button = ttk.Button(root, text="选择文件", command=upload_file)
upload_file_button.grid(row=1, column=0, padx=10, pady=10)

file_path_label = ttk.Label(root, text="当前未选择任何文件")
file_path_label.grid(row=1, column=1, padx=10, pady=10)

# 创建开始按钮
start_button = ttk.Button(root, text="开始", command=start_replay)
start_button.grid(row=2, columnspan=2, padx=10, pady=10)

root.mainloop()
